package com.ep.thirdPlatformProject.oa.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import com.ep.thirdPlatformProject.oa.entity.dto.EcologyEfficiencyRankDTO;
import com.ep.thirdPlatformProject.oa.entity.dto.EcologyFinishedWorkflowDTO;
import com.ep.thirdPlatformProject.oa.entity.vo.*;
import com.ep.thirdPlatformProject.oa.mapper.WorkflowHourMapper;
import com.ep.thirdPlatformProject.oa.mapstruct.EcologyReportConvertMapper;
import com.ep.thirdPlatformProject.oa.service.EcologyReportService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class EcologyReportServiceImpl implements EcologyReportService {


    private final WorkflowHourMapper workflowHourMapper;

    /**
     * 选择效率列表
     *
     * @return {@link List }<{@link EcologyEfficiencyRankDTO }>
     */
    @Override
    public PageInfo<EcologyEfficiencyRankDTO> selectEfficiencyList(EfficiencyRankParamVO vo) {
        PageHelper.startPage(vo.getCurrentPage(), vo.getPageSize());
        List<EcologyEfficiencyRankDTO> list = workflowHourMapper.selectWorkflowListVO(vo.getUserIds(), vo.getStartDate(), vo.getEndDate());
//        commonParamsDeal(vo);
        return new PageInfo<>(list);
    }

    /**
     * 选择待办工作流计数
     *
     * @return {@link List }<{@link EcologyTodoWorkflowVO }>
     */
    @Override
    public List<EcologyTodoWorkflowVO> selectTodoWorkflowCount(EfficiencyRankParamVO vo) {
        List<EcologyTodoWorkflowVO> result = new ArrayList<>();
        commonParamsDeal(vo);
        List<EcologyTodoWorkflowVO> list = workflowHourMapper.selectTodoWorkflowCount(vo.getUserIds(), vo.getStartDate(), vo.getEndDate());

        List<String> userIds = vo.getUserIds();
        List<EcologyCommonEmpInfoVO> vos = workflowHourMapper.selectEmpInfoByUserIds(userIds);
        for (EcologyCommonEmpInfoVO infoVO : vos) {
            EcologyReportConvertMapper mapper = EcologyReportConvertMapper.INSTANCE;
            EcologyTodoWorkflowVO target = mapper.convert2TodoAmountVO(infoVO);
            for (EcologyTodoWorkflowVO dto : list) {
                if (target.getEmpNo().equals(dto.getEmpNo())) {
                    int workflowCount = dto.getWorkflowCount();
                    target.setWorkflowCount(target.getWorkflowCount() + workflowCount);
                }
            }
            result.add(target);
        }
        return result;
    }

    /**
     * 选择已完成工作流计数
     *
     * @param vo 签证官
     * @return {@link List }<{@link EcologyFinishedWorkflowVO }>
     */
    @Override
    @SneakyThrows
    public List<EcologyFinishedWorkflowVO> selectFinishedWorkflowCount(EfficiencyRankParamVO vo) {
        List<EcologyFinishedWorkflowVO> result = new ArrayList<>();
        commonParamsDeal(vo);
        List<EcologyFinishedWorkflowDTO> list = workflowHourMapper.selectFinishedWorkflowCount(vo.getUserIds(), vo.getStartDate(), vo.getEndDate());
        List<String> userIds = vo.getUserIds();

        Map<String, Integer> map = list.stream().collect(Collectors.groupingBy(EcologyFinishedWorkflowDTO::getEmpNo,
                Collectors.summingInt(item -> item.getWorkflowCount() + 1)));

        List<EcologyCommonEmpInfoVO> vos = workflowHourMapper.selectEmpInfoByUserIds(userIds);
        for (EcologyCommonEmpInfoVO infoVO : vos) {

            EcologyReportConvertMapper mapper = EcologyReportConvertMapper.INSTANCE;
            EcologyFinishedWorkflowVO target = mapper.convert2workflowVO(infoVO);
            String empNo = target.getEmpNo();
            target.setWorkflowCount(map.getOrDefault(empNo, 0));
            result.add(target);
        }
        return result;
    }

    /**
     * 选择工作流程超时数
     *
     * @param vo 签证官
     * @return {@link List }<{@link EcologyTimeoutWorkflowVO }>
     */
    @Override
    public List<EcologyTimeoutWorkflowVO> selectWorkflowOutTimeCount(EfficiencyRankParamVO vo) {
        List<EcologyTimeoutWorkflowVO> result = new ArrayList<>();
        commonParamsDeal(vo);
        List<EcologyEfficiencyRankDTO> rankVOS = workflowHourMapper.selectWorkflowListVO(vo.getUserIds(), vo.getStartDate(), vo.getEndDate());
        List<String> userIds = vo.getUserIds();
        List<EcologyCommonEmpInfoVO> vos = workflowHourMapper.selectEmpInfoByUserIds(userIds);
        List<EcologyEfficiencyRankDTO> list = rankVOS.stream().filter(item -> item.getReduceTime() > 24).toList();
        for (EcologyCommonEmpInfoVO infoVO : vos) {
            EcologyReportConvertMapper mapper = EcologyReportConvertMapper.INSTANCE;
            EcologyTimeoutWorkflowVO target = mapper.convert2TodoTimeoutVO(infoVO);
            for (EcologyEfficiencyRankDTO dto : list) {
                if (target.getEmpNo().equals(dto.getEmpNo())) {
                    int workflowCount = target.getWorkflowCount();
                    workflowCount += 1;
                    target.setWorkflowCount(workflowCount);
                }
            }
            result.add(target);
        }

        return result;

    }

    /**
     * 选择工作流审核率
     *
     * @param vo 签证官
     * @return {@link List }<{@link EcologyEfficiencyRankDTO }>
     */
    @Override
    public List<EcologyWorkflowAuditRateVO> selectWorkflowAuditRate(EfficiencyRankParamVO vo) {

        List<EcologyWorkflowAuditRateVO> result = new ArrayList<>();
        // 获取所有的已办工作流
        List<EcologyFinishedWorkflowVO> finishedList = this.selectFinishedWorkflowCount(vo);
        // 获取所有待办的工作流
        List<EcologyTodoWorkflowVO> todoList = this.selectTodoWorkflowCount(vo);

        // 组装 根据编号分组，计算出所有审批率 PS：计算公式：（已办+待办）/已办
        for (EcologyFinishedWorkflowVO finishedItem : finishedList) {
            EcologyReportConvertMapper mapper = EcologyReportConvertMapper.INSTANCE;
            EcologyWorkflowAuditRateVO target = mapper.convert2TodoAuditRateVO(finishedItem);
            for (EcologyTodoWorkflowVO todoItem : todoList) {
                if (finishedItem.getEmpNo().equals(todoItem.getEmpNo())) {
                    int todoCount = todoItem.getWorkflowCount();
                    int finishedCount = finishedItem.getWorkflowCount();
                    target.setRate(String.valueOf(finishedCount == 0 ? 0 : (float) finishedCount / (todoCount + finishedCount)));
                }
            }
            result.add(target);
        }
        return result;
    }


    /**
     * 通用参数处理
     *
     * @param vo 签证官
     */
    private void commonParamsDeal(EfficiencyRankParamVO vo) {
        if (StrUtil.isEmpty(vo.getStartDate())) {
            var startDate = DateUtil.format(DateUtil.beginOfMonth(new Date()), DatePattern.NORM_DATETIME_FORMATTER);
            vo.setStartDate(startDate);
        }
        if (StrUtil.isEmpty(vo.getEndDate())) {
            var endDate = DateUtil.now();
            vo.setEndDate(endDate);
        }

    }


    private List<EcologyCommonEmpInfoVO> convertToCommonVO(EfficiencyRankParamVO vo) {
        List<EcologyCommonEmpInfoVO> result = new ArrayList<>();
        commonParamsDeal(vo);
        List<EcologyCommonEmpInfoVO> vos = workflowHourMapper.selectEmpInfoByUserIds(vo.getUserIds());


//        for (EcologyCommonEmpInfoVO infoVO : vos) {
//            EcologyReportConvertMapper mapper = EcologyReportConvertMapper.INSTANCE;
//            EcologyFinishedWorkflowVO target = mapper.convert2workflowVO(infoVO);
//            for (EcologyFinishedWorkflowDTO dto : list) {
//                if (target.getEmpNo().equals(dto.getEmpNo())) {
//                    int workflowCount = dto.getWorkflowCount();
//                    target.setWorkflowCount(target.getWorkflowCount() + workflowCount);
//                }
//            }
//            result.add(target);
//        }
        return List.of();
    }
}
